package net.vinote.smart.platform.service.handler;

import net.vinote.smart.platform.module.database.DBTransaction;
import net.vinote.smart.platform.module.database.bo.BizObject;
import net.vinote.smart.platform.service.dw.handler.CommonHandler;
import net.vinote.smart.platform.service.dw.handler.HandlerPerimissionAnnotation;
import net.vinote.smart.platform.service.util.Permission;
import net.vinote.smart.platform.service.util.Permission.PermissionEnum;

import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

@HandlerPerimissionAnnotation(
		insert = @Permission(PermissionEnum.SMART_CONTRACT_TEMPLATE_INSERT),
		update = @Permission(PermissionEnum.SMART_CONTRACT_TEMPLATE_UPDATE),
		query = @Permission(PermissionEnum.SMART_CONTRACT_TEMPLATE_QUERY),
		delete = @Permission(PermissionEnum.SMART_CONTRACT_TEMPLATE_DELETE))
public class ContractTemplateHandler extends CommonHandler {

	@Override
	protected void beforeInsert(BizObject bo, DBTransaction tx) {
		renderContent(bo);
	}

	@Override
	protected void beforeUpdate(BizObject bo, DBTransaction tx) {
		renderContent(bo);
	}

	/**
	 * 重新渲染合同模板,刷新输入域
	 * 
	 * @param bo
	 */
	private void renderContent(BizObject bo) {
		String content = bo.getAttribute("Content");
		Document templatteDoc = Jsoup.parseBodyFragment(content);
		Elements inputs = templatteDoc.select("input[type=text]");
		int index = 0;
		for (Element input : inputs) {
			String name = input.attr("name");
			if (StringUtil.isBlank(name)) {
				input.attr("name", "text_" + (++index));
			}
		}
		bo.setAttribute("Content", templatteDoc.body().html());
	}

	public static void main(String[] args) {
		ContractTemplateHandler handler = new ContractTemplateHandler();
		BizObject bo = new BizObject();
		bo.setAttribute("Content", "asdf<input type='text'/>asdf");
		handler.renderContent(bo);
		System.out.println(bo.getAttribute("Content"));
	}
}
